<template>
  <a-spin class="table-gl-con" style="margin-top: 10px" :loading="submitLoading">
    <TableWrap style="flex: 1" @refresh="getTableList">
      <template #headerLeft>
        <a-space>
          <p>共计 {{ total }} 条</p>
          <a-button type="primary" size="medium" @click="openEdt({})" v-if="$authPass('portfolios.create')">添加组合</a-button>
          <a-button class="gray-outline" size="medium" v-if="$authPass('portfolios.owner')" @click="openChooseUser">设置销售员</a-button>
        </a-space>
      </template>
      <template #tableBody>
        <a-table
          class="table-singe-line"
          ref="tableRef"
          row-key="id"
          :loading="tableLoading"
          @selection-change="selectColumn"
          :row-selection="rowSelection"
          :bordered="false"
          :data="tableList"
          :scroll="{
            x: 1720,
            y: '100%',
          }"
          size="mini"
          @sorter-change="sorterChange"
          :pagination="false"
        >
          <template #columns>
            <a-table-column :width="120" title="广告组合" fixed="left">
              <template #cell="{ record }">
                <p :class="record.state == 'archived' ? 'gray' : 'highlight'" class="cursor" @click="toCampaign(record)">{{ record.portfolioName }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="70" title="状态" fixed="left">
              <template #cell="{ record }">
                <p :class="$extract(statusMap[record.state], 'color')">{{ $extract(statusMap[record.state], 'name') }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="140" title="店铺" fixed="left" :tooltip="true" data-index="shopName" :ellipsis="true" />
            <a-table-column :width="70" title="销售员" fixed="left" data-index="ownerName" />
            <a-table-column :width="120" title="预算类型">
              <template #cell="{ record }">
                <template v-if="record.budgetPolicy == 'dateRange'">
                  <p>{{ record.budgetCurrencyCode }}{{ record.budgetAmount }}</p>
                  <p>日期范围</p>
                </template>
                <template v-else-if="record.budgetPolicy == 'monthlyRecurring'">
                  <p>{{ record.budgetCurrencyCode }}{{ record.budgetAmount }}</p>
                  <p>每月定期</p>
                </template>
                <p v-else>无预算上限</p>
              </template>
            </a-table-column>
            <!-- <a-table-column :width="140" title="今日预算使用占比" data-index="budgetUsagePercent" :sortable="sortable">
              <template #cell="{ record }">
                <a-progress style="width: 100px" :status="record.budgetUsagePercent > 80 ? 'warning' : 'normal'" :percent="Number((Number(record.budgetUsagePercent || 0) / 100).toFixed(2))" />
              </template>
            </a-table-column> -->
            <a-table-column :width="85" title="广告活动数" align="right" data-index="campaignNum" />
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="impressions">
              <template #title>
                <a-popover content="广告曝光次数">
                  <p>
                    <span>曝光量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" :sortable="sortable" align="right" data-index="clicks">
              <template #title>
                <a-popover content="广告点击次数">
                  <p>
                    <span>点击量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CTR" :sortable="sortable" align="right" data-index="ctr">
              <template #title>
                <a-popover content="广告点击转化率=点击量/曝光量">
                  <p>
                    <span>CTR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr || 0).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="90" title="花费" align="right" :sortable="sortable" data-index="cost">
              <template #title>
                <a-popover content="亚马逊广告花费">
                  <p>
                    <span>花费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cost || record.cost === 0">${{ Number(record.cost || 0).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPC" align="right" :sortable="sortable" data-index="cpc">
              <template #title>
                <a-popover content="单次点击成本，CPC=广告花费/点击量">
                  <p>
                    <span>CPC</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc || 0).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CVR" align="right" :sortable="sortable" data-index="cvr">
              <template #title>
                <a-popover content="广告转化率，CVR=广告订单量/点击量*100%">
                  <p>
                    <span>CVR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr || 0).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPA" align="right" :sortable="sortable" data-index="cpa">
              <template #title>
                <a-popover content="单笔订单平均广告花费，CPA=广告花费/广告订单量">
                  <p>
                    <span>CPA</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpa || record.cpa === 0">${{ Number(record.cpa || 0).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="总单量" align="right" :sortable="sortable" data-index="purchasesOrder">
              <template #title>
                <a-popover content="广告带来的订单及关联订单数量">
                  <p>
                    <span>总单量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesOrder || record.purchasesOrder === 0">{{ record.purchasesOrder }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="商品销量" align="right" :sortable="sortable" data-index="purchasesSale">
              <template #title>
                <a-popover content="广告商品销量">
                  <p>
                    <span>商品销量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="销售额" align="right" :sortable="sortable" data-index="saleAmount">
              <template #title>
                <a-popover content="广告带来的销售额及关联销售额">
                  <p>
                    <span>销售额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount || 0).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ACOS" align="right" :sortable="sortable" data-index="acos">
              <template #title>
                <a-popover content="投入产出比，ACOS=广告花费/广告销售额*100%">
                  <p>
                    <span>ACOS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.acos || record.acos === 0">{{ Number(record.acos || 0).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ROAS" align="right" :sortable="sortable" data-index="roas">
              <template #title>
                <a-popover content="支出回报，ROAS=广告销售额/广告花费">
                  <p>
                    <span>ROAS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.roas || record.roas === 0">{{ Number(record.roas || 0).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column title="操作" fixed="right">
              <template #cell="{ record }">
                <a-button type="text" @click="openEdt(record)" v-if="$authPass('portfolios.create')">编辑</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-spin>
  <!-- 添加/编辑组合 -->
  <AddPortfolio v-if="showPortfolioDialog" :currentData="currentData" :userList="userList" :markedtList="markedtList" :shopList="shopList" :isShow="showPortfolioDialog" @closed="showPortfolioDialog = false" @success="getTableList" />
  <!-- 匹配销售员 -->
  <ChooseUser v-if="showUserDialog" title="设置销售员" label="销售员" :list="userList" :multiple="false" :isShow="showUserDialog" :isRequired="true" @closed="showUserDialog = false" @success="editSales" />
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { getPortfoliosList, setPortfoliosOwner } from '@/api/advert'
  import AddPortfolio from './addPortfolio.vue'
  import ChooseUser from '@/components/ChooseUser.vue'
  import { Message } from '@arco-design/web-vue'
  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
    markedtList: {
      type: Array,
      default: () => [],
    },
    shopList: {
      type: Array,
      default: () => [],
    },
    userList: {
      type: Array,
      default: () => [],
    },
  })
  const emit = defineEmits(['toCampaign'])
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectRow = ref([])
  const statusMap = {
    enabled: { name: '投放中', color: 'success' },
    paused: { name: '已暂停', color: 'normal' },
    archived: { name: '已归档', color: 'gray' },
    ENABLED: { name: '投放中', color: 'success' },
    PAUSED: { name: '已暂停', color: 'normal' },
    ARCHIVED: { name: '已归档', color: 'gray' },
  }
  const showPortfolioDialog = ref(false)
  const showUserDialog = ref(false)
  const currentData = ref<any>({})
  const tableRef = ref()
  const submitLoading = ref(false)
  const tableListMap = ref({})

  // 进入广告活动
  function toCampaign(row: any) {
    emit('toCampaign', {
      portfolioId: row.portfolioId,
      portfolioName: row.portfolioName,
    })
  }
  function selectColumn(val: any) {
    selectRow.value = val
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function getTableListByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 获取组合列表数据
  async function getTableList() {
    if (!props.searchParams.startDate) return
    tableLoading.value = true
    const res: any = await getPortfoliosList({
      ...props.searchParams,
      ...searchVal.value,
    })
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.data || []
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      el.id = el.shopId + el.portfolioId
      tableListMap.value[el.id] = el
    })
    total.value = res?.data?.total || 0
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.orderItems = null
    } else {
      searchVal.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }
  // 打开匹配销售员
  function openChooseUser() {
    if (!selectRow.value.length) {
      return Message.error('请选择广告组合')
    }
    showUserDialog.value = true
  }
  // 编辑销售员
  async function editSales(users: any) {
    submitLoading.value = true
    let selectRows: Array<any> = []
    selectRow.value.map((id) => {
      selectRows.push(tableListMap.value[id])
    })
    let adjustPortfolioInfos: Array<string> = selectRows.map((el: any) => {
      return {
        shopId: el.shopId,
        portfoliosIds: [el.portfolioId],
      }
    })

    const res: any = await setPortfoliosOwner({
      ownerId: users,
      adjustPortfolioInfos: adjustPortfolioInfos,
    })
    submitLoading.value = false
    if (res) {
      Message.success('设置成功')
      getTableList()
    }
  }
  // 编辑组合
  function openEdt(row: any) {
    currentData.value = row
    showPortfolioDialog.value = true
  }
  defineExpose({ getTableListByVal })
</script>
<style lang="less" scoped>
  .table-gl-con {
    height: 100%;
  }
  .gray {
    color: #999;
  }
  .success {
    color: rgb(var(--success-5));
  }
  .normal {
    color: var(--color-text-2);
  }
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
  :deep(.arco-progress-line-text) {
    margin-left: 5px;
  }
</style>
